<?

    function getFormAjaxUpload($name, $link,$ons){
        ob_start();
        ?>
        <form action="<?=$link?>" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="<?=$ons?>">
                <p id="upload_form" align="center"><br/>
                    <p style="width:500px; text-align:left;">
                    <input type="radio" name="update_mode" value="1"> Импорт с группами<br>
                    <input type="radio" name="update_mode" value="2" checked>  Обновить название, описание и цены по артикулу<br>
                    </p>
                    <p style="width:500px; text-align:left;">
                    <input type="checkbox" name="clear_import">  Обновить полностью (<b>!заменит прайс!</b>)<br>
                    </p>
                    <label>Файл (<b>XLS</b>):  
                        <input name="<?=$name?>" type="file" size="30" />

                    </label>
                    <label>
                        <input type="submit" name="submitBtn" class="sbtn" value="Отправить" />
                    </label>
                    <input type="hidden" name="importFile" value="step" />
                </p>

            </form>
                <iframe id="upload_target" name="upload_target" src="/ADM/edit/?vid=cat&importFile=step&step=2" style="width:0;height:0;border:0px solid #fff;"></iframe>
        <?
        return ob_get_clean();
    }

if (isAjaxRequest && $_POST['importFile']){
        if (!empty($_POST['importFile'])) {
            ob_start();
            $value = $_POST['importFile'];
            $step = (empty($_GET['step']))?0:$_GET['step'];
            if ($value == 'dlg') {
                ?>                      
                <?= getFormAjaxUpload('importedFile', '/ADM/edit/?vid=cat&importFile=step&step=2', "startUpload()"); ?>
                <script language="javascript" type="text/javascript">
                    function startUpload(){
                        jQuery('.import_file_dlg .load_data').css('display','block');
                    }
                    function stopUpload(data){
                        jQuery('.import_file_dlg .data_container').html(data);
                    }
                </script>
                <?
            }if ($value == 'step') {
                if ($_GET['step'] == 2) {
                    $file_name = $_FILES['importedFile']['tmp_name'];
                    $content = explode("\n", file_get_contents($file_name));                    
                    unlink(LocalDir.'/import_price/price.xls');
                    move_uploaded_file($file_name, LocalDir.'/import_price/price.xls');
                    copy(LocalDir.'/import_price/price.xls', LocalDir.'/price/price.xls');
                    mysql_query('tuncate table tmp_cat');
                    mysql_query('tuncate table tmp_catalog');
                    mysql_query('delete from tmp_cat');
                    mysql_query('delete from tmp_catalog');
                    if (isset($_POST['clear_import'])){
                        mysql_query('tuncate table cat');
                        mysql_query('tuncate table catalog');
                        mysql_query('delete from cat');
                        mysql_query('delete from catalog');                        
                    }
                    exec('python ./import_price/smail.py>1');

                    if ($_POST['update_mode']==2){         
                            $posins=0;
                            $posupd=0;
                            $prods=  mysql_query('select * from tmp_catalog');
                            while ($p=  mysql_fetch_assoc($prods)){
                                $inreal=mysql_fetch_assoc(mysql_query('select id from catalog where art="'.$p['art'].'" limit 0,1'));
                                if (!isset($inreal['id'])){
                                    $posins++;
                                }else{
                                    mysql_query('update catalog set art=\''.$p['art'].'\',title=\''.$p['title'].'\',about=\''.$p['about'].'\',price='.$p['price'].',inexcel=1 where id='.$inreal['id']) or die(mysql_error());
                                    $posupd++;                                        
                                }
                            }
                            
                            ?>
                            <div id="result">                    
                                <?echo ' Импорт завершился удачно пропущено '.$posins.', обновлено '.$posupd.' позиций';?>
                            <script type="text/javascript">
                                jQuery('.import_file_dlg .load_data').css('display','none');
                                jQuery('.next_import').bind('click', function(){                                                    
                                    var dataItems=jQuery('.items_form').serialize();
                                    jQuery('.import_file_dlg .data_container').html('');
                                    jQuery('.import_file_dlg .load_data').css('display','block');
                                    jQuery.post("/ADM/edit/?vid=cat&importFile=step&step=3", dataItems, function(data){jQuery('.import_file_dlg .load_data').css('display','none');jQuery('.import_file_dlg .data_container').html(data)});

                                });
                            </script>
                            </div>
                        <script language="javascript" type="text/javascript">                                        
                            window.top.window.stopUpload(document.getElementById("result").innerHTML);
                        </script> 
                            <?
                        
                    }else{
                        $data = '';
                        $group['name'] = 'Общий';
                        $group['id'] = '0 or idparent<>0 ';
                        $c = mysql_fetch_assoc(mysql_query('select count(id) as c from cat where idparent=' . $group['id']));
                        $subs = '';
                        if ($c['c'] > 0) {
                            $subs.=', имеет подгрупп ' . $c['c'] . ' необходимо указать подгруппу для каждой позиции, либо выбрать общую для всех ' . select::FromTable('forAllSub', 'asi_cat_groups', 'idparent=' . $group['id']) . '<br/><br/>';
                        }
                        ?>
                        <div id="result">                    
                            <form class="items_form">
                                <?
                                    $groups= mysql_fetch_assoc(mysql_query('select count(id) as c from tmp_cat'));
                                    echo '<h2>Найдено '.$groups['c'].' групп/подгрупп сопоставте с существующими</h2>'
                                ?>
                                <table width="100%">
                                <?
                                    $groups=  mysql_query('select * from tmp_cat');
                                    $i=0;
                                    while ($gr=  mysql_fetch_assoc($groups)){
                                        if ($gr['parent']==0)
                                            echo '<tr><td>'.$gr['title'].'<input type="hidden" name="tmpgr'.$i.'" value="'.$gr['id'].'" /></td>';
                                        else
                                            echo '<tr><td>--'.$gr['title'].'<input type="hidden" name="tmpgr'.$i.'" value="'.$gr['id'].'" /></td>';
                                        echo '<td><select name="real_gr'.$i.'" style="width:150px;"><option value="-1">Новая группа</option><option value="-999">Пропустить группу</option>';
                                        $reals=  mysql_query('select * from cat');
                                        while ($r=  mysql_fetch_assoc($reals)){
                                            $sel='';
                                            if ($r['title']==$gr['title'])
                                                $sel='selected="selected"';
                                            echo '<option value="'.$r['id'].'" '.$sel.'>'.$r['title'].'</option>';
                                        }
                                        echo '</select></td></tr>';
                                        $i++;
                                    }
                                ?>     
                                </table>
                                <input type="hidden" name="importFile" value="step" />
                            </form>
                            <input class="next_import" type="button" value="Далее >" style="float:right;" />
                            <script type="text/javascript">
                                jQuery('.import_file_dlg .load_data').css('display','none');
                                jQuery('.next_import').bind('click', function(){                                                    
                                    var dataItems=jQuery('.items_form').serialize();
                                    jQuery('.import_file_dlg .data_container').html('');
                                    jQuery('.import_file_dlg .load_data').css('display','block');
                                    jQuery.post("/ADM/edit/?vid=cat&importFile=step&step=3", dataItems, function(data){jQuery('.import_file_dlg .load_data').css('display','none');jQuery('.import_file_dlg .data_container').html(data)});

                                });
                            </script>
                        </div>
                        <script language="javascript" type="text/javascript">                                        
                            window.top.window.stopUpload(document.getElementById("result").innerHTML);
                        </script> 
                        <?          
                    }
                }elseif ($_GET['step'] == 3) {
                    if (isset($_POST['tmpgr0'])){
                        $i=0;
                        $upd=0;
                        $posins=0;
                        $posupd=0;
                        mysql_query('update catalog set inexcel=0');
                        mysql_query('update cat set inexcel=0');
                        while (isset($_POST['tmpgr'.$i])){
                            $tmpid=$_POST['tmpgr'.$i];
                            $realid=$_POST['real_gr'.$i];
                            if ($realid==-999){
                                mysql_query('delete from tmp_catalog where cat='.$tmpid);
                                mysql_query('delete from tmp_cat where id='.$tmpid);
                            }else{
                                mysql_query('update tmp_cat set sys_group='.$realid.' where id='.$tmpid) or die(mysql_error());
                                mysql_query('update cat set inexcel=1 where id='.$realid) or die(mysql_error());
                                if ($realid==-1){
                                    $ngr=  mysql_fetch_assoc(mysql_query('select title,parent from tmp_cat where id='.$tmpid));
                                    mysql_query('insert into cat (parent, title) values('.$ngr['parent'].',\''.$ngr['title'].'\')');
                                    $realid=  mysql_insert_id();
                                    mysql_query('update tmp_cat set sys_group='.$realid.' where id='.$tmpid) or die(mysql_error());
                                    $par_group= mysql_fetch_assoc(mysql_query('select parent from tmp_cat where id='.$tmpid));
                                    if (!empty($par_group['parent'])){
                                        $syspar_group= mysql_fetch_assoc(mysql_query('select sys_group from tmp_cat where id='.$par_group['parent']));                                        
                                        if ($syspar_group['sys_group']>0){
                                            mysql_query('update cat set parent='.$syspar_group['sys_group'].' where id='.$realid) or die(mysql_error());
                                            mysql_query('update cat set inexcel=1 where id='.$realid) or die(mysql_error());
                                        }
                                    }

                                }
                                $upd++;
                                $prods=  mysql_query('select * from tmp_catalog where cat='.$tmpid);
                                while ($p=  mysql_fetch_assoc($prods)){
                                    $inreal=mysql_fetch_assoc(mysql_query('select id from catalog where art="'.$p['art'].'" limit 0,1'));
                                    foreach ($p as $d=>$val){
                                        $p[$d]=  str_ireplace("'", "\\'", $val);
                                        $p[$d]=  str_ireplace('"', '\\"', $val);
                                    }
                                    if (!isset($inreal['id'])){
                                        mysql_query('insert into catalog (art,title,about,price,cat,inexcel) values("'.$p['art'].'","'.$p['title'].'","'.$p['about'].'",'.$p['price'].','.$realid.', 1)') or die(mysql_error());
                                        $posins++;
                                    }else{
                                        mysql_query('update catalog set art=\''.$p['art'].'\',title=\''.$p['title'].'\',about=\''.$p['about'].'\',price='.$p['price'].',cat='.$realid.',inexcel=1 where id='.$inreal['id']) or die(mysql_error());
                                        
                                        $posupd++;                                        
                                    }
                                }
                                mysql_query('update cat set inexcel=1 where id='.$realid) or die(mysql_error());
                                $pp=mysql_fetch_assoc(mysql_query('select * from cat where id='.$realid));
                                mysql_query('update cat set inexcel=1 where id='.$pp['parent']);
                            }
                            $i++;
                        }
                    }
                    echo ' Импорт завершился удачно добавлено '.$posins.', обновлено '.$posupd.' позиций в '.$upd.' группах.';
                    mysql_query('delete from cat where inexcel=0');
                    mysql_query('delete from catalog where inexcel=0');
                }                
            }
            echo ob_get_clean();
        }
        exit();
    }
    if (!isAjaxRequest && empty($path[3])){
        ob_start();
        print_r($path);
        ?>
        <link href="/css/jquery-ui-1.8.custom.css" rel="stylesheet" type="text/css" />
        <link href="/css/tree/tree.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="/js/jquery-ui-1.8.16.custom.min.js" ></script>
        <script type="text/javascript" src="/js/jquery.ui.datepicker-ru.js" ></script>
        
        <script type="text/javascript" src='/js/jquery.jstree.js'></script>
        
        <?
           $selected='organization_info';
           $init_open='"'.$selected.'"';
           $menu='';
           $i=0;
           $roots=mysql_query('select * from cat where inexcel=1 and (parent is null or parent=0)');
           while ($root= mysql_fetch_assoc($roots)){
                $type=$root['id'];
                $name=$root['title'];
                if (!empty($_GET['data'])&&$type==$_GET['data']){
                    $selected=$type;
                    $init_open='"'.$type.'"';
                }
                $menu.='
                    <li id="'.$type.'">
                        <a href="/ADM/edit/'.$root['id'].'/?vid=cat&data='.$type.'">'.$name.'</a>';
                $subs=  mysql_query('select * from cat where inexcel=1 and parent='.$root['id']);
                $menu.='<ul>';
                while ($sub=  mysql_fetch_assoc($subs)){
                    $type=$sub['id'];
                    $name=$sub['title'];
                    $menu.='
                        <li id="'.$type.'">
                            <a href="/ADM/edit/'.$sub['id'].'/?vid=cat&data='.$type.'">'.$name.'</a>';
                    $menu.='</li>';
                    
                }
                $menu.='</ul>';
                $menu.='</li>';
                $i++;

           }
 	       

        ob_start();
        ?>
        <table style="width:100%; table-layout: fixed;">
            <tr><td width="250">
            <div class="sel-item" style="height: 500px; overflow: scroll; width: 250px;">
                <div style="width:220px; height:100%;">
                    <div id="scrollbar1" style="height:100%;">
                        <div class="scrollbar"><div class="track"><div class="thumb"><div class="end" ></div></div></div></div>        
                        <div class="viewport">
                            <div class="overview">
                                <div id="admin_items_menu" class="admin_items_menu" name="admin_items_menu">
                                    <ul>
                                        <?= $menu ?>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                                
                </div>
            </div>
                </td><td>
                    <div style="width:100%;" class="sub_content">
        <input type="button" value="Импорт файла" class="import_file_btn" />
        <div class="import_file_dlg">
            <div class="load_data" style="position:absolute; left:center; top:center; text-align: center; display:block; width:100%;  left:0; top:40%; z-index: 100;">Обработка...<br/><img src="/images/loader.gif" /></div>
            <div class="data_container"></div>
        </div>

        <script type="text/javascript">            
                            
            jQuery('.import_file_dlg').dialog({autoOpen:false,
                modal: true, 
                width:800,
                height:400
            });
            jQuery('.import_file_btn').bind('click', function(){
                jQuery('.import_file_dlg .load_data').css('display','block');
                jQuery('.import_file_dlg').dialog('open');
                                 
                jQuery('.import_file_dlg .data_container').html('');
                jQuery('.import_file_dlg .data_container').load("", {importFile:"dlg"}, function(){
                    jQuery('.import_file_dlg .load_data').css('display', 'none');
                });
            })

            </script>                        
                    </div>
                </td>        
            </tr>
        </table>
                <script type="text/javascript">
                var simpleTreeCollection;
                var Mn;
                var interval=null;
                jQuery(document).ready(function() {

                    
                    jQuery('#admin_items_menu a').each(function(){                    
                        jQuery(this).bind('click', function(){
                            var url=jQuery(this).attr('href');                            
                            jQuery('.sub_content').load(url,function(d){jQuery('.sub_content').html(d)});
                            
                        })
                    });
                    var tree=jQuery("#admin_items_menu").jstree({ 
                        "themes" : {
                            "theme" : "apple",
                            "dots" : false,
                            "icons" : true
                        }, 
                        "ui":{
                            "select_limit" : 2,
                            "select_multiple_modifier" : "alt",
                            "selected_parent_open": true,
                            "selected_parent_close" : "select_parent",
                            "initially_select" : [ "<?=$selected?>" ]
                        },
                        "core" : { "initially_open" : [ <?=$init_open?> ] },
                        "plugins" : [ "themes", "html_data", "ui" ],
                        callback: {
                            onselect: function(NODE, TREE_OBJ) {
                                alert(NODE.id);
                            }
                        }

                    });
                    
            });


        </script>
        <?
        echo ob_get_clean();
        return;
    }
    
?>
<script type="text/javascript">
var $d = jQuery.noConflict();

	$d(document).ready(function() {

		// Указываем дейтпикеру что выводить все нужно на русском
		$d.datepicker.setDefaults($d.datepicker.regional['ru']);
		$d.datepicker.setDefaults($d.datepicker.formatDate('yyyy-mm-dd'));
		$d('#date').datepicker();
		
	});	
	
	// скрытие всяких элементов
	$d(document).ready(function(){
    $d(".btn-slide").click(function(){
        $d("#panel").slideToggle("slow");
        return false;
    });
});


</script>
<?
// дату сегодня
if (empty($info['date']) or $info['date']=='0000-00-00') $info['date'] = date("Y-m-d");

?>

        <input type="button" value="Импорт файла" class="import_file_btn" />
        <div class="import_file_dlg">
            <div class="load_data" style="position:absolute; left:center; top:center; text-align: center; display:block; width:100%;  left:0; top:40%;">Обработка...<br/><img src="/images/loader.gif" /></div>
            <div class="data_container"></div>
        </div>

        <script type="text/javascript">            
                            
            jQuery('.import_file_dlg').dialog({autoOpen:false,
                modal: true, 
                width:800,
                height:400
            });
            jQuery('.import_file_btn').bind('click', function(){
                jQuery('.import_file_dlg .load_data').css('display','block');
                jQuery('.import_file_dlg').dialog('open');
                                 
                jQuery('.import_file_dlg .data_container').html('');
                jQuery('.import_file_dlg .data_container').load("", {importFile:"dlg"}, function(){
                    jQuery('.import_file_dlg .load_data').css('display', 'none');
                });
            })

            
            </script>                        

<form action="<? echo $info['url']; ?>" method="post" enctype="multipart/form-data">

    

<label>    <input name="show" type="checkbox" value="<?=$info['show']?>" checked="checked" />
          Отображать на сайте</label><br /><br />
 
<strong>Название категории/подкатегории:</strong><br />
      
      <textarea name="title" style="width:250px;" cols="50"><?=$info['title']?></textarea><br />     <br />
      
      
      
<strong>Родительский элемент:</strong><br /><br />
<select name="parent" style="width:250px;">
<?
$parents = array();
$parents['/'] = 'Верхний уровень';
$z = mysql_query("select * from cat");
while ($t = mysql_fetch_assoc($z)) {
        if (!empty($t['parent'])){
            $t['title']='---'.$t['title'];
            $parents[$t['id'].'" disabled="disabled'] = $t['title'];
        }else
            $parents[$t['id']] = $t['title'];
}
$parents['/'] = 'Верхний уровень';
foreach ($parents as $p=>$tit) {
	echo '<option';
	if ($info['parent'] == $p) echo ' selected="selected"';
	echo ' value="'.$p.'">'.$tit.'</option>';
}

?>
</select><br/><br/>
<?
    $subs= mysql_fetch_assoc(mysql_query('select count(id) as c from cat where parent='.$info['id']));
    $items= mysql_fetch_assoc(mysql_query('select count(id) as c from catalog where inexcel=1 and cat='.$info['id']));
    echo '<b>Подгрупп в группе - '.$subs['c'].'</b><br/>';
    if ($items['c']>0){
        $add='&nbsp;<a href="/catalog/group/'.$info['id'].'">Перейти к товарам группы >></a>';
    }
    echo '<b>Товаров в группе - '.$items['c'].'</b>'.$add;
?>
      <br/>
      <br/>

<input type="submit" value="Сохранить">
